package com.itheima.a20;

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;

/**
 * @author: AirMan
 * @date: 2025/4/16 13:49
 * @description:
 */
public class MyA20 {
    public static void main(String[] args) throws Exception {

        AnnotationConfigServletWebServerApplicationContext context =
                new AnnotationConfigServletWebServerApplicationContext(MyWebConfig.class);
        context.register(Controller1.class);
        RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        System.out.println(">>>>>>>>>>>>>>>>>>>" + handlerMethods);
        handlerMethods.forEach((k, v) -> {
            System.out.println(k + "=" + v);
        });

        MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/test4");
        request.setParameter("name", "冉涛涛");
        request.addHeader("token", UUID.randomUUID().toString().replaceAll("-", ""));
        MockHttpServletResponse response = new MockHttpServletResponse();
        HandlerExecutionChain chain = handlerMapping.getHandler(request);
        System.out.println("chain" + " = " + chain);

        RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
        Method method = adapter.getClass().getDeclaredMethod("invokeHandlerMethod", HttpServletRequest.class, HttpServletResponse.class, HandlerMethod.class);
        method.setAccessible(true);

        method.invoke(adapter, request, response, chain.getHandler());

        byte[] content = response.getContentAsByteArray();
        System.out.println(new String(content, StandardCharsets.UTF_8));

    }
}
